/**
 * @name excode
 * 兑换码
 */

/**
 * @name config
 * @param string key 激活码
 * 获取并检查兑换码
 */
exports.config = function () {
    let id = this.get('id','string');
    let excodeData;
    let excodeModel = this.model.branch('excode',this.branch);
    return excodeModel.get(id).then(ret=>{
        if(!ret){
            return this.error("excode_not_exist",id);
        }
        excodeData = ret;
        let cid = ret["cid"];
        let configModel = this.model.branch('config',this.branch);
        return configModel.get(cid)
    }).then(config=>{
        if(!config){
            return this.error('excode config not exist');
        }
        if(config['multi'] > 0 && excodeData['use'] >= config['multi'] ){
            return this.error('excode_multi_limit',excodeData['use']);
        }
        return {"_id":config['_id'],"cid":config['cid'],"key":excodeData["_id"], "item":config['item'],"repeat":config['repeat'] };
    })
}

/**
 * @name submit
 * @param string key 激活码
 * 将兑换码状态设置为已经使用
 */
exports.submit = function () {
    let key = this.get('key','string');
    if(  !key  ){
        return this.error('args empty');
    }
    let codeModel = this.model.branch('excode',this.branch);
    return codeModel.incr(key,'use',1);
}
